// pages/user/info-edit/info-edit.ts
import { validateNull, formatTime } from '../../../utils/util';
import userBaseInfoState from '../../../stores/userBaseInfo';
import { getPatientBaseObject, modPatientBaseObject } from '../../../utils/api/patientBase';
import Notify from '@vant/weapp/notify/notify';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: <PatientBaseEntity>{
      patientName: <string | null>'张三',
      identificationNumber: <string | null>'122053165',
      sex: <string | null>'男性',
      birthday: <string | null>'1990-01-01',
      phoneNumber: '13131888098'
    },
    tmpbirthday: 0,
    isShowSexSelect: false,
    sexList: ['男性', '女性'],
    isShowDate: false,
    maxDate: new Date().getTime(),
    minDate: new Date(1910, 0, 1).getTime(),
    formatter(type: string, value: any) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
  },

  showSexSelect() {
    this.setData({
      isShowSexSelect: true,
    })
  },
  cancelSexSelect() {
    this.setData({
      isShowSexSelect: false,
    })
  },
  changeSex(event: any) {
    const { picker, value, index } = event.detail;
    this.data.user.sex = value
    this.setData({
      user: this.data.user
    })
    console.log('确认性别:', this.data.user.sex);
    this.cancelSexSelect()
  },
  showDate() {
    this.setData({
      isShowDate: true,
    })
  },
  cancelDate() {
    this.setData({
      isShowDate: false,
    })
  },
  changeBirthday(event: any) {
    this.setData({
      tmpbirthday: event.detail
    })
  },
  confirmBirthday() {
    // 将时间戳变为日期
    let date1 = new Date(this.data.tmpbirthday);
    this.data.user.birthday = formatTime(date1, 'yyyy-MM-dd')
    this.setData({
      user: this.data.user,
    })
    this.cancelDate()
  },
  modUserInfo() {
    const data = <PatientBaseEntity>{
      patientUid: userBaseInfoState.data.patientUid,
      physicalStrength: userBaseInfoState.data.physicalStrength,
      phoneNumber: userBaseInfoState.data.phoneNumber,
      wxUid: userBaseInfoState.data.wxUid,
      username: userBaseInfoState.data.username,
      patientName: this.data.user.patientName,
      identificationNumber: this.data.user.identificationNumber,
      sex: this.data.user.sex,
      birthday: this.data.user.birthday
    };
    console.log(data);
    modPatientBaseObject(data).then((res: any) => {
      console.log('修改基本信息成功', res);
      Notify({ type: 'success', message: '修改成功' });
      // 更新用户基本信息
      this.getUserInfo()

    }).catch((err: any) => {
      console.log("修改基本信息失败", err);
      wx.showToast({
        title: '信息修改失败',
        icon: 'loading',
        duration: 2000
      });
    })
  },
  onInput(event: any) {
    // 先判断类型
    const type = (event.currentTarget.dataset.type || '').toString().trim();
    if (type == 'name') {
      this.data.user.patientName = event.detail
    } else if (type == 'identificationNumber') {
      this.data.user.identificationNumber = event.detail
    } else if (type == 'sex') {
      this.data.user.sex = event.detail
    } else if (type == 'birthday') {
      this.data.user.birthday = event.detail
    } else if (type == 'phoneNumber') {
      this.data.user.phoneNumber = event.detail
    } else {
      // 出现错误
      console.log('输入错误');
      return;
    }

    this.setData({
      user: this.data.user
    })
  },
  // 需要更新用户基本信息数据，所以需要重新获取
  getUserInfo() {
    const data = <PatientBaseEntity>{ wxUid: wx.getStorageSync("openid") };
    getPatientBaseObject(data).then((res: any) => {
      console.log('获取基本信息成功', res);
      userBaseInfoState.onChangeData(res.data[0])
      this.setData({
        user: userBaseInfoState.data
      })
    }).catch((err: any) => {
      console.log("获取基本信息失败", err);
    })
  },

  // onInput(event: any) {
  //   const { field } = event.currentTarget.dataset;
  //   userBaseInfoState.updateField(field, event.detail);
  //   this.setData({
  //     [`user.${field}`]: event.detail
  //   });
  // },

  onConfirm() {
    this.modUserInfo();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    userBaseInfoState.bind(this, '$userBase');
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})